<template>
    <div class="container_box">
        <el-scrollbar ref="scrollbarRef" class="main_box">
            <div class="created_link">
                <el-form ref="formRef" :model="form" :rules="rules" label-width="110px">
                    <!-- 分组 -->
                    <el-form-item label="分组" prop="group">
                        <el-cascader
                            ref="cascaderRef"
                            v-model="form.group"
                            style="width: 500px"
                            :options="groupData"
                            :props="defaultProps"
                            placeholder="请选择分组"
                            @change="orgChange" />
                    </el-form-item>
                    <!-- 标题 -->
                    <el-form-item label="链接标题" prop="title">
                        <el-input
                            v-model="form.title"
                            style="width: 500px"
                            maxlength="20"
                            show-word-limit
                            placeholder="请输入链接标题"></el-input>
                    </el-form-item>
                    <!-- 连接描述 -->
                    <el-form-item label="链接描述" prop="linkDesc">
                        <el-input
                            v-model="form.linkDesc"
                            style="width: 500px"
                            type="textarea"
                            :rows="3"
                            maxlength="30"
                            show-word-limit
                            placeholder="请输入链接描述"></el-input>
                    </el-form-item>
                    <!-- 上传文件 -->
                    <ZWUpload ref="emptyData" :up-info="picInfo" @submit="getFileList" />
                    <!-- <ZWUpload :upInfo="picInfo" @submit="getFileList" v-if="!router.currentRoute.value.query.type" /> -->
                    <!-- <Upload :cover="'cover'" ref="emptyData" @submit="getFileList" v-if="router.currentRoute.value.query.type" :key="componentKey" /> -->
                    <!--链接内容-->
                    <el-form-item label="链接内容" prop="content">
                        <tinymce-editor
                            id="editor"
                            ref="editorRef"
                            v-model:value="form.content"
                            style="width: 1200px"
                            :is-oss="true">
                        </tinymce-editor>
                    </el-form-item>
                    <el-form-item>
                        <template #label>
                            <div class="label_text">
                                <span>素材标签</span>
                                <el-tooltip :content="tagTips.materialTagTips" placement="top">
                                    <img src="@/assets/image/material/question.png" alt="" />
                                </el-tooltip>
                            </div>
                        </template>
                        <selectTags ref="tagIdsRef" v-model="form.tag_ids" />
                    </el-form-item>
                    <el-form-item label="是否强制授权">
                        <el-radio-group v-model="form.is_force_grant" @change="changeAuth">
                            <el-radio :label="1">否</el-radio>
                            <el-radio :label="2">是</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item v-show="form.is_force_grant == 2" label="授权内容">
                        <el-checkbox-group v-model="form.grant_params">
                            <el-checkbox label="offical_headimg_nickname">头像昵称（公众号）</el-checkbox>
                            <el-checkbox label="phone">手机号（小程序）</el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item>
                        <template #label>
                            <div class="label_text">
                                <span>浏览打标</span>
                                <el-tooltip :content="tagTips.browseCustTips" placement="top">
                                    <img src="@/assets/image/material/question.png" alt="" />
                                </el-tooltip>
                            </div>
                        </template>
                        <selectTags ref="viewtagIdsRef" v-model="form.view_tag_ids" :type="2" />
                    </el-form-item>
                    <el-form-item>
                        <template #label>
                            <div class="label_text">
                                <span>分享打标</span>
                                <el-tooltip :content="tagTips.shareCustTips" placement="top">
                                    <img src="@/assets/image/material/question.png" alt="" />
                                </el-tooltip>
                            </div>
                        </template>
                        <selectTags ref="shareTagIdsRef" v-model="form.share_tag_ids" :type="2" />
                    </el-form-item>

                    <el-form-item label="">
                        <div class="agree_ment">
                            <!-- 暂时隐藏掉,协议要先不上需要法务确认 -->

                            <!-- <el-checkbox v-model="form.check"></el-checkbox>
          <span class="ml2">勾选代表同意</span>
          <el-link class="form-link" type="primary" :underline="false">《***用户协议》</el-link> -->
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </el-scrollbar>
        <div class="footer_box">
            <el-button plain @click="cancelHandel">取消</el-button>
            <!-- <el-button plain :disabled="!form.check">预览</el-button> -->
            <el-button :type="form.check ? 'primary' : 'info'" :disabled="!form.check" @click="submitHandel">
                保存
            </el-button>
        </div>
    </div>
</template>
<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue';
import ZWUpload from '../components/ZWUpload.vue';
import TinymceEditor from '@/components/TinymceEditor.vue';
import selectTags from '../../../components/selectTags.vue';
import { ElForm } from 'element-plus';
import { createLink } from '@/api/concreation';
import { ElMessage } from 'element-plus';
import router from '@/router';
import { linkInfos, updateLink, getGroupList } from '@/api/concreation';
import { getSetionId, IsNotEmpty } from '@/utils/utils';
import { useRoute } from 'vue-router';
import { useStore } from '@/store';
import { nextTick } from 'process';
const emptyData = ref();
const route = useRoute();
const formRef = ref<InstanceType<typeof ElForm>>();
const cascaderRef: any = ref(null); // 选择分组ref
const store = useStore();
const editorRef = ref();
const uploadTitle = ref('上传文件');
const uploadVisib = ref(false);
const isEdit = ref(false);
const uploadSelectRef = ref(null);
const tagType = ref(1);
const tagIdsRef = ref(null);
const viewtagIdsRef = ref(null);
const shareTagIdsRef = ref(null);

const tagTips = {
    materialTagTips: '该素材会被打上此素材标签，在列表上会展示',
    browseCustTips: '浏览该素材的客户将被打上此客户标签',
    shareCustTips: '点击该素材的分享按钮并生成分享链接的客户将被打上此客户标签'
};
// 分组列表
const groupData = ref([]);
// 1-文本 2-图片 3-音频 4-视频 5-文件 6-链接文章 7-链接引用
const type = computed(() => {
    return store.getters['content/type'];
});
//上传弹框
const uploadInfo = computed(() => {
    return store.getters['content/upload'];
});
// 分组列表
const group: any = computed(() => {
    return store.getters['content/group'];
});
//标签
const tags = computed(() => {
    return store.getters['content/tagsInfo'].tags;
});

/**
 * @description: 获取分组数据
 * @return {*}
 */
const getGroupListFunc = async () => {
    try {
        const res = await getGroupList({ type: 6 });
        groupData.value = res.data;
    } catch (error) {
        // to do error
    }
};
const componentKey = ref(0);
const groupId = ref(0);
const defaultProps = {
    checkStrictly: true,
    emitPath: false,
    label: 'name',
    value: 'id'
};

const form = reactive({
    tag_ids: [],
    view_tag_ids: [],
    is_force_grant: 1,
    group: 0, //分组
    type: 0,
    images: '', // 图片
    tags: [], //标签
    check: true, //用户协议
    title: '', //标题
    link: '', //链接地址
    linkDesc: '', // 连接描述
    id: '', //内容id
    content: '',
    share_tag_ids: [],
    grant_params: ['offical_headimg_nickname', 'phone']
});
const rules = reactive({
    group: [{ required: true, message: '请选择分组', trigger: 'change' }],
    title: [
        {
            required: true,
            message: '链接标题不能为空',
            trigger: 'blur'
        }
    ],
    link: [
        {
            required: true,
            message: '链接地址不能为空',
            trigger: 'blur'
        }
    ],
    content: [
        {
            required: true,
            message: '链接内容不能为空',
            trigger: 'blur'
        }
    ],
    linkDesc: [
        {
            required: true,
            message: '链接描述不能为空',
            trigger: 'blur'
        }
    ],
    images: [
        {
            required: true,
            message: '封面不能为空',
            trigger: 'click'
        }
    ]
});
// 图片上传
const picInfo = reactive({
    type: 1,
    label: '封面',
    prop: 'images',
    files: form.images,
    multiple: true,
    limitSize: 2,
    limitNum: 1,
    // acceptFile: '.jpg,.jpeg,.png,.bmp,.webp'
    acceptFile: '.jpg,.JPG,.jpeg,.JPEG,.png,.PNG'
});
// 获取上传成功的文件
const getFileList = (data: any) => {
    data = data.filter((item: any) => IsNotEmpty(item));
    form.images = data.length > 0 ? data[0].code : '';
    formRef?.value?.validateField('images');
};
// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};
const changeAuth = () => {
    if (form.is_force_grant == 1) {
        form.grant_params = [];
    } else {
        form.grant_params = ['offical_headimg_nickname', 'phone'];
    }
};
// 取消
const cancelHandel = () => {
    formRef.value.resetFields();
    router.push({ path: '/content/basematerial/link', query: { groupId: route.query?.groupId } });
};
//确定
const submitHandel = () => {
    formRef.value.validate(async (valid: any) => {
        if (valid) {
            const groupId = form.group;
            const grant = {
                offical_headimg_nickname: form.grant_params.includes('offical_headimg_nickname') ? 2 : 1,
                phone: form.grant_params.includes('phone') ? 2 : 1
            };
            if (router.currentRoute.value.query.val) {
                const params = {
                    tag_ids: getSetionId('id', form.tag_ids),
                    view_tag_ids: getSetionId('id', form.view_tag_ids),
                    title: form.title,
                    group_id: form.group,
                    file_type: form.type,
                    code: '',
                    media_content_id: form.id,
                    link: form.link,
                    desc: form.linkDesc,
                    cover_code: form.images,
                    content: form.content,
                    is_force_grant: form.is_force_grant,
                    grant_params: grant,
                    share_tag_ids: getSetionId('id', form.share_tag_ids)
                };
                updateLink({ ...params, type: router.currentRoute.value.query.val }).then((data: any) => {
                    isEdit.value = false;
                    ElMessage.success('修改链接成功');
                    forceRerender();
                    router.push({ path: '/content/basematerial/link', query: { groupId: groupId } });
                    // router.go(-1);
                });
                return;
            }
            const params = {
                title: form.title,
                desc: form.linkDesc,
                content: form.content,
                group_id: form.group,
                code: form.images,
                tag_ids: getSetionId('id', form.tag_ids),
                view_tag_ids: getSetionId('id', form.view_tag_ids),
                is_force_grant: form.is_force_grant,
                grant_params: grant,
                share_tag_ids: getSetionId('id', form.share_tag_ids)
            };
            try {
                //创建链接
                createLink(params).then((data: any) => {
                    formRef.value.resetFields();
                    router.push({ path: '/content/basematerial/link', query: { groupId: groupId } });
                    ElMessage.success('创建链接成功！');
                });
            } catch (e) {
                ElMessage.error('创建链接失败！');
            }
        }
    });
};
const forceRerender = () => {
    componentKey.value += 1;
};
watch(uploadInfo, uploadInfo => {
    uploadTitle.value = uploadInfo.title;
    uploadVisib.value = uploadInfo.uploadVisib;
    form.grant_params = ['offical_headimg_nickname', 'phone'];
    form.is_force_grant = 1;
});

watch(tags, data => {
    form.tags = data;
});

const editItem = () => {
    const params = {
        media_content_id: router.currentRoute.value.query.id
    };
    linkInfos(params).then((data: any) => {
        Object.assign(form, data);
        // tag_ids 素材标签
        // view_tag_ids 浏览客户标签
        // share_tag_ids 分享客户标签
        form.tag_ids = data.tag_info;
        form.view_tag_ids = data.view_tag_info;
        form.share_tag_ids = data.share_tag_info;
        form.linkDesc = data.desc;
        form.group = data.group_id;
        form.content = data.link_info.content;
        form.tags = data.tag_info;
        form.images = data.link_info.cover_image_url;
        form.is_force_grant = data.is_force_grant;
        form.grant_params = [];
        if (data.grant_params.offical_headimg_nickname == 2) {
            form.grant_params.push('offical_headimg_nickname');
        }
        if (data.grant_params.phone == 2) {
            form.grant_params.push('phone');
        }
        emptyData.value.echo(data.link_info);
        setTimeout(() => {
            tagIdsRef.value?.init();
            viewtagIdsRef.value?.init();
            shareTagIdsRef.value?.init();
        }, 0);
    });
};
if (router.currentRoute.value.query.val) {
    editItem();
}
watch(
    () => form.images,
    () => {
        if (router.currentRoute.value.query.val) {
            formRef.value.validateField('cover');
        }
    }
);
onMounted(async () => {
    await getGroupListFunc();
    form.group = +route.query?.groupId;
    groupId.value = form.group;
    store.dispatch('content/changeType', 7);
});
</script>
<style lang="scss" scoped>
.created_link {
    padding: 24px;
}

.radio_list {
    &_item {
        &_icon {
            width: 14px;
            height: 14px;
            margin: -3px 0 0 6px;

            img {
                margin-top: 2px;
                width: 100%;
                height: 100%;
                vertical-align: top;
            }
        }
    }

    :deep .el-radio__label {
        display: flex;
        align-items: center;
    }
}

.ml2 {
    margin-left: 2px;
}

.mr10 {
    margin-right: 10px;
}

.agree_ment {
    display: flex;
    align-items: center;
}

.btn_group {
    text-align: right;
    margin-top: 15px;
    background-color: #fff;
    padding: 10px;
}

:deep(.el-form-item) {
    .label_text {
        display: flex;
        align-items: center;
        gap: 6px;

        img {
            width: 14px;
            height: 14px;
        }
    }
}
</style>
